<template>
  <div class="login-container">
    <video
      data-v-cc6c3120=""
      muted="muted"
      src="../../statics/videos/bg-video.mp4"
      loop="loop"
      autoplay="autoplay"
      class="video"
    ></video>
    <div class="bg"></div>

    <el-form
      :model="loginForm"
      status-icon
      :rules="rules"
      ref="loginForm"
      label-width="100px"
      class="login-loginForm"
      ><i
        @click="iserweilogin = !iserweilogin"
        :class="[
          'jiaobiao',
          'iconfont',
          iserweilogin ? 'icon-diannaojiaobiao' : 'icon-erweimajiaobiao',
        ]"
      ></i>
      <h1 class="title">管理系统</h1>
      <!-- //常规登录 -->
      <div class="normal-login" v-if="!iserweilogin">
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="loginForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <el-input v-model="loginForm.captcha" class="captcha"></el-input
          ><span
            id="captcha-svg"
            v-html="captchasvg"
            @click="updateCaptcha"
          ></span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('loginForm')"
            >提交</el-button
          >
        </el-form-item>
      </div>
      <!-- //二维码登录 -->
      <div class="erwei-login" v-else></div>
    </el-form>
  </div>
</template>
<script>
//引入api中方法
import * as api from "../../api";
//验证码验证
var validateCaptcha = (rule, value, callback) => {
  //callback只要传参了,表示表单验证不通过,不传参表示表单验证通过
  //value就是在input中输入的值
  //rule是个对象,即验证对象
  if (value.length !== 5) {
    callback("验证码必须是5位");
  } else {
    callback();
  }
};
//用户名验证
var valitateUsername = (rule, value, callback) => {
  //callback只要传参了,表示表单验证不通过,不传参表示表单验证通过
  //value就是在input中输入的值
  //rule是个对象,即验证对象
  let reg = /^\w{3,12}$/;
  if (reg.test(value)) {
    //验证通过
    callback();
  } else {
    callback("用户名可以是数字字母下划线,3-12位");
  }
};
//密码验证
var validatePass = (rule, value, callback) => {
  if (value.length < 3) {
    callback("密码长度不能小于3");
  } else {
    callback();
  }
};
export default {
  data() {
    return {
      iserweilogin: false, //是否是二维码登录
      loginForm: {
        username: "",
        password: "",
        captcha: "",
      },
      captchasvg: "", //验证码svg
      rules: {
        username: [{ validator: valitateUsername, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }],
        captcha: [{ validator: validateCaptcha, trigger: "blur" }],
      },
    };
  },
  created() {
    this.updateCaptcha();
  },
  methods: {
    //封装一个获取二维码地址的方法
    getQrcode() {
      //关掉qrcode的遮罩
      this.isScanCodeSuccess = false;
      //让遮罩的样式初始化
      this.qrStyle.backgroundImage = `url(${codeSuccessImg})`;
      //从本地取出sid
      let sid = localStorage.getItem("qf-sid");
      if (!sid) {
        this.$message.error("没有sid");
        return;
      }
      api.getQrcodeUrlApi(sid).then((res) => {
        //更改qrtip的提示
        this.qrtip = "请使用手机微信扫码登入";
        // console.log(res);
        let qrUrl = res.data.scanCodeUrl;
        //3.通过qrcode将二维码地址生成二维码
        qrcode.toDataURL(qrUrl, (err, dataUrl) => {
          // console.log(dataUrl);
          this.qrDataUrl = dataUrl;
        });
      });
    },
    ...mapMutations(["SET_USER_INFO"]),
    //封装一个方法,专门用于获取验证码
    updateCaptcha() {
      api.getCaptchaApi().then((res) => {
        // console.log(res.data);
        this.captchaSvg = res.data.img;
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        //所有的表单校验通过之后,那么valid的值是true
        //不然valid的布尔值就是false

        //1.先校验本地的表单是否通过
        //2.校验验证码是否正确
        //3.校验用户名密码是否正确

        if (valid) {
          //表单校验通过了
          //打开Loading动画
          const loading = this.$loading({
            lock: true,
            text: "正在登入...",
            spinner: "iconfont icon-jiazaizhong",
            background: "rgba(0, 0, 0, 0.7)",
          });
          //校验验证码 验证码都是小写,所以把用户传入的通通转成小写
          api
            .verifyCaptcha(this.loginForm.captcha.toLowerCase())
            .then((res) => {
              // console.log(res)
              if (res.data.state) {
                //验证码通过
                //继续校验用户名和用户密码
                api
                  .loginApi(this.loginForm.username, this.loginForm.password)
                  .then((res) => {
                    // console.log(res.data)
                    if (res.data.state) {
                      loading.close(); //关闭加载动画
                      this.$message.success({
                        message: "登入成功,正在跳转...",
                        type: "success",
                        duration: 1000,
                      });
                      //登入成功
                      //1.将token储存到本地
                      localStorage.setItem("qf-token", res.data.token);
                      //2.将userInfo存到本地
                      localStorage.setItem(
                        "qf-userInfo",
                        JSON.stringify(res.data.userInfo)
                      );
                      //按钮权限
                      //按钮权限
                      localStorage.setItem(
                        "permissionButtons",
                        JSON.stringify(res.data.permission.buttons)
                      );
                      //3.将用户信息添加到vuex
                      this.SET_USER_INFO(res.data.userInfo);
                      //4.跳转到主页
                      this.$router.push("/");
                    } else {
                      //登入失败,用户名或者密码错误
                      // alert("账户或者密码错误")
                      loading.close(); //关闭加载动画
                      //this.$message.error("账号或者密码错误");
                    }
                  });
              } else {
                // console.log('验证码错误');
                loading.close(); //关闭加载动画
                //this.$message.error("验证码错误");
                //清空验证码输入框的内容
                this.loginForm.captcha = "";
                //让输入框获得焦点
                this.$refs.captcha.focus();
                //验证码错误,刷新验证码
                this.updateCaptcha();
              }
            });
        } else {
          //表单校验不通过
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>
<style lang="scss" scoped>
.login-container {
  .jiaobiao {
    font-size: 60px;
    position: absolute;
    right: -1px;
    top: -1px;
    opacity: 0.7;
    cursor: pointer;
  }
  .video {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
  }
  .bg {
    background-image: url("../../statics/images/bg.png");
    background-repeat: no-repeat;
    position: fixed;
    width: 20%;
    height: 40%;
    background-size: 100% 100%;
    left: 20%;
    top: 40%;
    opacity: 0.5;
  }
  .login-loginForm {
    position: fixed;
    right: 10%;
    top: 25%;
    border-radius: 5px;
    width: 400px;
    background-color: rgba(0, 0, 0, 0.3);
    padding: 100px 0 50px 0;
    color: #fff;
    .title {
      text-align: center;
      padding: 30px 0;
    }
    ::v-deep .el-form-item__label {
      color: #fff;
    }
    .el-input {
      width: 250px;
    }
    .el-button {
      width: 250px;
      background: linear-gradient(90deg, #1596fb, #002dff);
    }
    #captcha-svg {
      position: absolute;
      right: 50px;
      top: -5px;
      cursor: pointer;
    }
  }
}
</style>
